#include "LegacyMotionImporterDialog.h"
#include "ui_LegacyMotionImporterDialog.h"

#include <boost/filesystem.hpp>
#include <MMM/Model/ModelReaderXML.h>
#include <QFileDialog>
#include <QCheckBox>
#include <QSettings>
#include <QListWidget>
#include <QMessageBox>
#include <set>
#include "../../common/HandleMotionsWithoutModel.h"

LegacyMotionImporterDialog::LegacyMotionImporterDialog(MMM::LegacyMotionConverterPtr converter, QWidget* parent) :
    QDialog(parent),
    ui(new Ui::LegacyMotionImporterDialog),
    converter(converter)
{
    ui->setupUi(this);

    motionList = new MotionListWidget(converter->getMotionNames());

    ui->motionListLayout->addWidget(motionList);

    connect(ui->importMotionButton, SIGNAL(clicked()), this, SLOT(importMotion()));
    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(close()));
}

LegacyMotionImporterDialog::~LegacyMotionImporterDialog() {
    delete ui;
}

void LegacyMotionImporterDialog::importMotion() {
    handleMotionsWithoutModel();
    try {
        motions = converter->convertMotions(motionList->getConfigurations());
        if (motions.size() > 0) {
            this->close();
        } else {
            QMessageBox* msgBox = new QMessageBox(this);
            msgBox->setText(QString("Please enable minimum one motion!"));
            msgBox->exec();
        }
    } catch (MMM::Exception::MMMException& e) {
        QMessageBox* msgBox = new QMessageBox(this);
        msgBox->setText(QString::fromStdString(e.what()));
        msgBox->exec();
    }
}

void LegacyMotionImporterDialog::handleMotionsWithoutModel() {
    for (auto legacyMotionWithoutModel : converter->getMotionsWithoutModel()) {
        MMM::ModelReaderXMLPtr mr(new MMM::ModelReaderXML());
        std::string modelFilePath = legacyMotionWithoutModel->getModelFilePath();
        handleMissingModelFilePath(modelFilePath);

        if (!modelFilePath.empty()) {
            legacyMotionWithoutModel->setModelFilePath(modelFilePath);
            MMM::ModelPtr model = mr->loadModel(modelFilePath);
            if (model) {
                if (legacyMotionWithoutModel->getModelProcessor()) {
                    legacyMotionWithoutModel->setModel(legacyMotionWithoutModel->getModelProcessor()->convertModel(model), model);
                }
                else legacyMotionWithoutModel->setModel(model, model);
            }
        }
        else throw MMM::Exception::MMMException("Model for " + legacyMotionWithoutModel->getMotionFilePath() + " was not set!");
    }
}

MMM::MotionList LegacyMotionImporterDialog::getMotions() {
    exec();
    return motions;
}
